// 核心模块 - 提供基础类型和工具

use std::sync::Arc;
use std::sync::Mutex;
use log::info;

// 导入safe_ffi库
use safe_ffi::core::types::{CapabilityId, ResourceType};

// 能力包装器（安全地管理exokernel能力）- 简化版本
pub struct CapabilityWrapper {
    id: CapabilityId,
    #[allow(dead_code)]
    resource_type: ResourceType,
    acquired: bool,
}

impl CapabilityWrapper {
    // 创建新的能力包装器
    pub fn new(id: CapabilityId, resource_type: ResourceType) -> Self {
        CapabilityWrapper {
            id,
            resource_type,
            acquired: false,
        }
    }

    // 获取能力
    pub fn acquire(&mut self) -> bool {
        if !self.acquired {
            self.acquired = true;
            info!("Capability {} acquired", self.id);
            true
        } else {
            info!("Capability {} already acquired", self.id);
            true
        }
    }

    // 释放能力
    pub fn release(&mut self) {
        if self.acquired {
            self.acquired = false;
            info!("Capability {} released", self.id);
        }
    }

    // 获取能力ID
    pub fn id(&self) -> CapabilityId {
        self.id
    }

    // 检查是否已获取
    pub fn is_acquired(&self) -> bool {
        self.acquired
    }
    
    // 获取内部能力引用（简化版本）
    pub fn get_inner(&self) -> Arc<()> {
        Arc::new(())
    }
}

impl Drop for CapabilityWrapper {
    fn drop(&mut self) {
        self.release();
    }
}

// 服务特征定义
pub trait Service: Send + Sync {
    fn name(&self) -> &'static str;
    fn start(&mut self) -> Result<(), String>;
    fn stop(&mut self) -> Result<(), String>;
    fn status(&self) -> ServiceStatus;
}

// 服务状态枚举
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceStatus {
    Stopped,
    Starting,
    Running,
    Stopping,
    Error(String),
}

// 服务管理器特征
pub trait ServiceManager: Send + Sync {
    fn register_service(&mut self, service: Arc<Mutex<dyn Service>>) -> Result<(), String>;
    fn start_service(&self, name: &str) -> Result<(), String>;
    fn stop_service(&self, name: &str) -> Result<(), String>;
    fn get_service_status(&self, name: &str) -> Option<ServiceStatus>;
    fn list_services(&self) -> Vec<String>;
}

// 错误类型定义
#[derive(Debug)]
pub enum ServiceError {
    InitializationFailed(String),
    OperationFailed(String),
    ServiceNotFound(String),
    CapabilityError(String),
}

impl std::fmt::Display for ServiceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceError::InitializationFailed(msg) => write!(f, "Service initialization failed: {}", msg),
            ServiceError::OperationFailed(msg) => write!(f, "Service operation failed: {}", msg),
            ServiceError::ServiceNotFound(name) => write!(f, "Service not found: {}", name),
            ServiceError::CapabilityError(msg) => write!(f, "Capability error: {}", msg),
        }
    }
}

impl std::error::Error for ServiceError {}

// 配置管理
pub mod config;
pub use config::*;

// 工具函数
pub mod utils;
pub use utils::*;